// pages/addProduct/shareproducts/shareProduct.js
var app = getApp();
const utilService = require('../../../utils/utilService.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
      addressData: null,      // 地址
      leibie:"",       // 类别
      myPics: [],      // 图片地址
      picArray: [],    // 图片数组（仅仅图片地址  不包含video pic字段）
      myVidios: '',    // 视频地址
      titleStr:'',     // 标题
      describeStr:'',  // 描述
      isNew:'0',     // 是否全新
      isUploadedVideo: false, // 是否已上传视频
      firstPic:'', // 首图
      leftPicCount:5, //剩余可选照片
      shareMsg:"",
      weight: '',        // 货物重量
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    this.getShareMessage(8)
    // wx.getSetting({//先获取用户当前的设置  
    //   success(res) {
    //     if (!res.authSetting['scope.address']) {
    //       wx.authorize({
    //         scope: 'scope.address',
    //         success(res) {
    //           console.log(res.errMsg);//用户授权后执行方法  
    //         },
    //         fail(res) {
    //           //用户拒绝授权后执行  
    //         }
    //       })
    //     }
    //   }
    // })
    app.loginPromise.then(() => {
      var param = {
        userId: getApp().globalData.userId,
      }
      console.log(param)
      getApp().func.Get(false, getApp().api.getDefault_address, param,
        function (data) {
          if (data != '') {
            that.setData({
              addressData: data,
            })
          }
        },
        function (error) {
          wx.showToast({
            title: error.data.message,
            icon: 'none',
            duration: 2000,
          })
        })
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var leibie = this.data.leibie;
    this.setData({
      leibie:leibie,
    })
  },
  //获取分享信息
  getShareMessage: function (type) {
    var self = this;
    utilService.shareSettings(type,
      function (data) {
        console.log("分享数据", data)
        self.setData({
          shareMsg: data.title
        })
      },
      function (error) {

      }
    );
  },

  /**
    * 用户点击右上角分享
    */
  onShareAppMessage: function (res) {
    var title = this.data.shareMsg
    var path = "pages/home/home?userId=" + getApp().globalData.userId
    return {
      title: title,
      path: path,
      success: function (res) {
      },
      fail: function (res) {
      }
    }
  },
  addPictureClick: function (e) {
    this.showTost('点击了上传图片');
    this.uploadPhoto(e)
  },

  uploadPhoto: function (e) {
    console.log(e.currentTarget.dataset.type)
    let that = this;
    if (that.data.isUploadedVideo == true && that.data.myPics.length >=6){
      this.showTost('图片最多上传5张', 'none');
      return
    } else if (that.data.isUploadedVideo == false && that.data.myPics.length >= 5){
      this.showTost('图片最多上传5张', 'none');
      return
    } else if (that.data.leftPicCount <= 0){
      this.showTost('图片最多上传5张', 'none');
      return
    }
    // 上传图片
    wx.chooseImage({
      count: that.data.leftPicCount,
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        if ((that.data.isUploadedVideo == true && that.data.picArray.length > 1) || (that.data.isUploadedVideo == false && that.data.picArray.length > 0)){
          that.setData({// 存储首图地址
            firstPic: that.data.picArray[0]
          })
        }else{
          that.setData({// 存储首图地址
            firstPic: tempFilePaths[0]
          })
        }

        that.setData({
          leftPicCount: that.data.leftPicCount - tempFilePaths.length
        })
        console.log(res)
        
        var array = that.data.myPics
        for (var index in res.tempFilePaths) {
          array.push({"type" : "img", "src" : res.tempFilePaths[index]})
        }

        that.setData({
          myPics: array, 
          picArray: that.data.picArray.concat(tempFilePaths) 
          
        })

      },
    });
  },

  addVideoClick: function () {
    var that = this
    let videos=[]
    let video = []
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: function (res) {
        if (res.duration>30){
          that.showTost('视频大于30秒', 'none');
          return
        }
        videos = [{ type: 'video', src: res.tempFilePath }]
        video = [res.tempFilePath]
        if (that.data.isUploadedVideo){// 已经上传过视频，直接替换以前的地址
          that.data.myPics[0].src = res.tempFilePath
          that.data.picArray[0] = res.tempFilePath
          // 视频截图
          // that.data.picArray[1] = res.thumbTempFilePath
          that.setData({
            myPics: that.data.myPics,
            picArray: that.data.picArray,

          })
        }else{// 没上传过视频，上传新的视频
          that.setData({
            myPics: videos.concat(that.data.myPics),
            picArray: video.concat(that.data.picArray),
            isUploadedVideo: true
          })
        }

      }
    })
  },


  /**
   * 移除图片
   */
  removePhoto: function (e) {
    let idx = e.currentTarget.dataset.idx;
    if (this.data.isUploadedVideo){
      if (e.currentTarget.dataset.idx == 0){
        this.setData({ isUploadedVideo:false})
      }
    }
    this.data.myPics.splice(idx, 1);
    this.data.picArray.splice(idx, 1);
    this.setData({
      myPics: this.data.myPics,
      picArray: this.data.picArray,
      leftPicCount: this.data.leftPicCount + 1,
    })
  },
  /**
     * 移除视频
     */
  removeVidio: function (e) {
    let idx = e.currentTarget.dataset.idx;
    this.data.myVidios.splice(idx, 1);
    this.setData({
      myVidios: this.data.myVidios
    })
    console.log(this.data.myVidios)
  },
  switchChange: function (e) {
    if (e.detail.value){
      this.setData({ isNew: '1' })
    }else{
      this.setData({ isNew: '0' })
    }
    
  },
  locationClick: function (e) {
    var that = this;
    wx.navigateTo({
      url: '../myAddress/myAddres',
    })
  },
  showTost: function (str, icon) {
    wx.showToast({
      title: str,
      icon: icon != null ? icon : 'succes',
      duration: 1000,
      mask: true
    })
  },

/**
 * 输入的重量
 */
  bindKeyInput: function (e) {
    if (e.detail.value.length > 5){
      this.setData({
        weight: this.data.weight
      })
      return
    }
    this.setData({
      weight: e.detail.value
    })
    console.log(this.data.weight)
  },
  
  /**
   * 点击下一步
   */
  nextClick:function(e) {
    // 获取表单id
    let formId = e.detail.formId;
    console.log("formId-1", formId)
    getApp().saveUserFormId(formId,1);

    if (this.data.titleStr == ''){
      this.showTost('请添加标题', 'none');
    } else if (this.data.describeStr == ''){
      this.showTost('请添加描述', 'none');
    } else if (this.data.myPics.length == 0 || (this.data.isUploadedVideo == true && this.data.myPics.length == 1)){
      this.showTost('请添加照片', 'none');
    } else if (this.data.addressData == null){
      this.showTost('请添加地址', 'none');
    } else if (!this.data.weight ) {
      this.showTost('请添加物品重量', 'none');
    } else if (this.data.weight <= 0) {
      this.showTost('请输入正确物品重量', 'none');
    }else{
      wx.navigateTo({
        url: '../publishDetails/publishDetail?sharedData=' + encodeURIComponent(JSON.stringify(this.data)),
      })
    }
        // }
      // wx.navigateTo({
      //   url: '../compileProduct/compipleProduct',
      // })
  },
  titleInput:function(e){
    this.setData({ titleStr: e.detail.value})
  },
  describeInput:function(e){
    this.setData({ describeStr: e.detail.value })
  }
  
})